package String;

public class 找出字符串中第一个匹配项的下标 {
    public int strStr(String haystack, String needle) {
        if (needle.length() > haystack.length()) return -1;
        int[] next = getNext(needle);
        for (int i = 0, j = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) j = next[j - 1];
            if (haystack.charAt(i) == needle.charAt(j)) j++;
            if (j == needle.length()) return i - needle.length() + 1;
        }
        return -1;
    }

    private int[] getNext(String s) {
        int[] next = new int[s.length()];
        next[0] = 0;
        for (int i = 0, j = 1; j < s.length(); j++) {
            while (i > 0 && s.charAt(i) != s.charAt(j)) i = next[i - 1];
            if (s.charAt(i) == s.charAt(j)) i++;
            next[j] = i;
        }
        return next;
    }
}
